<template>
    <div class="leave-adjustment-form">
        <!-- <router-link to="/main/renshi/renshizhidu" class="back-link">返回</router-link> -->
        <div class="header-actions">
            <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
            <span>
                <el-button type="success" icon="el-icon-check" @click="saveData" v-if="!isView">保存</el-button>
                <el-button type="" icon="el-icon-menu" @click="goToList">列表</el-button>
                <el-button type="info" icon="el-icon-printer" @click="printForm">打印</el-button>
            </span>
        </div>
        <h2 class="form-title">调休申请单</h2>
        <table class="form-table" border="1">
            <tr>
                <td>工号</td>
                <td><input v-model="formData.employeeId" :disabled="isView" /></td>
                <td>姓名</td>
                <td><input v-model="formData.employeeName" :disabled="isView" /></td>
            </tr>
            <tr>
                <td>组别</td>
                <td><input v-model="formData.group" :disabled="isView" /></td>
                <td>岗位</td>
                <td><input v-model="formData.position" :disabled="isView" /></td>
            </tr>
            <tr>
                <td>事由</td>
                <td colspan="3"><textarea v-model="formData.reason" :disabled="isView"></textarea></td>
            </tr>
            <tr>
                <td rowspan="2">上班日期</td>
                <td>开始</td>
                <td>
                    <input style="width:80px;" v-model="formData.workStartDate.year" type="number" min="0"
                        :disabled="isView" /> 年
                    <input style="width:60px;" v-model="formData.workStartDate.month" type="number" min="0"
                        :disabled="isView" /> 月
                    <input style="width:60px;" v-model="formData.workStartDate.day" type="number" min="0"
                        :disabled="isView" /> 日
                    <input style="width:60px;" v-model="formData.workStartDate.hour" type="number" min="0"
                        :disabled="isView" /> 时
                    <input style="width:60px;" v-model="formData.workStartDate.minute" type="number" min="0"
                        :disabled="isView" /> 分
                </td>
                <td rowspan="2">
                    <button @click="clearWorkDate" v-if="!isView" class="clear-button">清空</button>
                </td>
            </tr>
            <tr>
                <td>结束</td>
                <td>
                    <input style="width:80px;" v-model="formData.workEndDate.year" type="number" min="0"
                        :disabled="isView" /> 年
                    <input style="width:60px;" v-model="formData.workEndDate.month" type="number" min="0"
                        :disabled="isView" /> 月
                    <input style="width:60px;" v-model="formData.workEndDate.day" type="number" min="0"
                        :disabled="isView" /> 日
                    <input style="width:60px;" v-model="formData.workEndDate.hour" type="number" min="0"
                        :disabled="isView" /> 时
                    <input style="width:60px;" v-model="formData.workEndDate.minute" type="number" min="0"
                        :disabled="isView" /> 分
                </td>
            </tr>
            <tr>
                <td rowspan="2">休息日期</td>
                <td>开始</td>
                <td>
                    <input style="width:80px;" v-model="formData.restStartDate.year" type="number" min="0"
                        :disabled="isView" /> 年
                    <input style="width:60px;" v-model="formData.restStartDate.month" type="number" min="0"
                        :disabled="isView" /> 月
                    <input style="width:60px;" v-model="formData.restStartDate.day" type="number" min="0"
                        :disabled="isView" /> 日
                    <input style="width:60px;" v-model="formData.restStartDate.hour" type="number" min="0"
                        :disabled="isView" /> 时
                    <input style="width:60px;" v-model="formData.restStartDate.minute" type="number" min="0"
                        :disabled="isView" /> 分
                </td>
                <td rowspan="2">
                    <button @click="clearRestDate" v-if="!isView" class="clear-button">清空</button>
                </td>
            </tr>
            <tr>
                <td>结束</td>
                <td>
                    <input style="width:80px;" v-model="formData.restEndDate.year" type="number" min="0"
                        :disabled="isView" /> 年
                    <input style="width:60px;" v-model="formData.restEndDate.month" type="number" min="0"
                        :disabled="isView" /> 月
                    <input style="width:60px;" v-model="formData.restEndDate.day" type="number" min="0"
                        :disabled="isView" /> 日
                    <input style="width:60px;" v-model="formData.restEndDate.hour" type="number" min="0"
                        :disabled="isView" /> 时
                    <input style="width:60px;" v-model="formData.restEndDate.minute" type="number" min="0"
                        :disabled="isView" /> 分
                </td>
            </tr>
            <tr>
                <td>申请人</td>
                <td><input v-model="formData.applicant" :disabled="isView" /></td>
                <td>班组复核</td>
                <td><input v-model="formData.groupReviewer" :disabled="isView" /></td>
            </tr>
            <tr>
                <td>部门负责人审核</td>
                <td><input v-model="formData.departmentReviewer" :disabled="isView" /></td>
                <td>部长/总监签批</td>
                <td><input v-model="formData.directorApprover" :disabled="isView" /></td>
            </tr>
            <tr>
                <td>总经理审批</td>
                <td><input v-model="formData.generalManagerApprover" :disabled="isView" /></td>
                <td>企业管理部意见</td>
                <td><input v-model="formData.managementDepartmentOpinion" :disabled="isView" /></td>
            </tr>
            <tr>
                <td>总裁/董事长核准</td>
                <td colspan="3">
                    <input style="width:150px;" v-model="formData.presidentApprover" :disabled="isView" />
                    签名/日期：<input style="width:150px;" v-model="formData.presidentApproverDate" type="date"
                        :disabled="isView" />
                </td>
            </tr>
        </table>
        <div class="instructions">
            <p>说明：</p>
            <ol>
                <li>此单必须由申请人本人填写；</li>
                <li>休息日期、上班日期不能跨月，同时必须为全天调休；</li>
                <li>签批权限：员工级由部门负责人审核后交企业管理部生效；职员主管级及以下人员由分公司部长/总监/总经理签批后生效；职员经理级（含）以上人员由总裁核准后生效。</li>
            </ol>
        </div>
        <p class="form-info">
            <span>表单编号及版本：AM - JY - 008 A/1</span>
            <span>保存期限：长期</span>
        </p>
    </div>
</template>

<script>
import { getLeaveAdjustmentDetail, saveLeaveAdjustment } from '@/api/leaveAdjustment';
import { Message } from 'element-ui';

export default {
    data() {
        return {
            pageType: 'add', // add, edit, view
            formData: {
                id: null,
                employeeId: '',
                employeeName: '',
                group: '',
                position: '',
                reason: '',
                workStartDate: {
                    year: new Date().getFullYear().toString(),
                    month: (new Date().getMonth() + 1).toString(),
                    day: new Date().getDate().toString(),
                    hour: '9',
                    minute: '0'
                },
                workEndDate: {
                    year: new Date().getFullYear().toString(),
                    month: (new Date().getMonth() + 1).toString(),
                    day: new Date().getDate().toString(),
                    hour: '18',
                    minute: '0'
                },
                restStartDate: {
                    year: '',
                    month: '',
                    day: '',
                    hour: '',
                    minute: ''
                },
                restEndDate: {
                    year: '',
                    month: '',
                    day: '',
                    hour: '',
                    minute: ''
                },
                applicant: '',
                groupReviewer: '',
                departmentReviewer: '',
                directorApprover: '',
                generalManagerApprover: '',
                managementDepartmentOpinion: '',
                presidentApprover: '',
                presidentApproverDate: '',
                status: 'pending'
            }
        };
    },
    computed: {
        isView() {
            return this.pageType === 'view';
        }
    },
    created() {
        this.initPageData();
    },
    methods: {
        printForm() {
            window.print()
        },

        goBack() {
            this.$router.push('/main/renshi/renshizhidu')
        },

        // 初始化页面数据
        async initPageData() {
            const { id, type } = this.$route.query;
            if (type) {
                this.pageType = type;
            }

            if (id) {
                try {
                    const response = await getLeaveAdjustmentDetail(id);
                    if (response.data && response.data.code === 200) {
                        this.formData = response.data.data;
                    } else {
                        Message.error(response.data.message || '获取详情失败');
                    }
                } catch (error) {
                    console.error('获取详情错误：', error);
                    Message.error('获取详情失败：' + error.message);
                }
            }
        },

        clearWorkDate() {
            this.formData.workStartDate = {
                year: '',
                month: '',
                day: '',
                hour: '',
                minute: ''
            };
            this.formData.workEndDate = {
                year: '',
                month: '',
                day: '',
                hour: '',
                minute: ''
            };
        },

        clearRestDate() {
            this.formData.restStartDate = {
                year: '',
                month: '',
                day: '',
                hour: '',
                minute: ''
            };
            this.formData.restEndDate = {
                year: '',
                month: '',
                day: '',
                hour: '',
                minute: ''
            };
        },

        // 验证表单
        validateForm() {
            if (!this.formData.employeeId) {
                Message.error('请填写工号');
                return false;
            }

            if (!this.formData.employeeName) {
                Message.error('请填写姓名');
                return false;
            }

            if (!this.formData.group) {
                Message.error('请填写组别');
                return false;
            }

            if (!this.formData.position) {
                Message.error('请填写岗位');
                return false;
            }

            if (!this.formData.reason) {
                Message.error('请填写事由');
                return false;
            }

            // 验证上班日期
            if (!this.validateDateFields(this.formData.workStartDate, '上班开始日期') ||
                !this.validateDateFields(this.formData.workEndDate, '上班结束日期')) {
                return false;
            }

            // 验证休息日期
            if (!this.validateDateFields(this.formData.restStartDate, '休息开始日期') ||
                !this.validateDateFields(this.formData.restEndDate, '休息结束日期')) {
                return false;
            }

            // 验证上班日期和休息日期不能跨月
            if (!this.validateSameMonth(this.formData.workStartDate, this.formData.workEndDate, '上班日期') ||
                !this.validateSameMonth(this.formData.restStartDate, this.formData.restEndDate, '休息日期')) {
                return false;
            }

            if (!this.formData.applicant) {
                Message.error('请填写申请人');
                return false;
            }

            return true;
        },

        // 验证日期字段是否完整
        validateDateFields(dateObj, fieldName) {
            if (!dateObj.year || !dateObj.month || !dateObj.day || !dateObj.hour || !dateObj.minute) {
                Message.error(`请填写完整的${fieldName}`);
                return false;
            }
            return true;
        },

        // 验证日期是否在同一个月内
        validateSameMonth(startDate, endDate, fieldName) {
            if (startDate.year && startDate.month && endDate.year && endDate.month) {
                if (startDate.year !== endDate.year || startDate.month !== endDate.month) {
                    Message.error(`${fieldName}不能跨月`);
                    return false;
                }
            }
            return true;
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/tiaoxiusq/tiaoxiusqList');
        },
        // 保存数据
        async saveData() {
            if (!this.validateForm()) {
                return;
            }

            try {
                const response = await saveLeaveAdjustment(this.formData);
                if (response.data && response.data.code === 200) {
                    Message.success('保存成功');
                    this.$router.push('/main/renshi/renshizhidu/tiaoxiusq/tiaoxiusqList');
                } else {
                    Message.error(response.data.message || '保存失败');
                }
            } catch (error) {
                console.error('保存错误：', error);
                Message.error('保存失败：' + error.message);
            }
        }
    }
};
</script>

<style scoped lang="scss">
.leave-adjustment-form {
    font-family: '宋体', sans-serif;
    padding: 20px;
     background-color: #f9f9f9; 
    // border-radius: 8px;
    /* box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); */
    width: 210mm;
    margin: 0 auto;
    min-height: 100vh;
}

.header-actions {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.back-link {
    text-decoration: none;
    color: #409EFF;
    font-weight: bold;
    position: absolute;
    top: 10px;
    left: 10px;
}

.back-link:hover {
    text-decoration: underline;
}

.save-button,
.list-button,
.clear-button {
    padding: 8px 16px;
    background-color: #409EFF;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.save-button:hover,
.list-button:hover,
.clear-button:hover {
    background-color: #66b1ff;
}

.form-title {
    text-align: center;
    color: #333;
    margin-bottom: 20px;
    font-size: 1.2em;
}

.form-table {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 20px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

.form-table th,
.form-table td {
    border: 1px solid #ddd;
    padding: 12px;
    text-align: center;
    font-size: 1em;
    font-family: '宋体';
}

.form-table th {
    background-color: #f2f2f2;
}

.instructions {
    margin-bottom: 20px;
    text-align: left;
}

.instructions ol {
    padding-left: 20px;
    text-align: left;
    line-height: 2em;
    list-style-position: inside;
    text-indent: 0.1em;
}

.form-info {
    display: flex;
    justify-content: space-between;
    color: #767676;
}

input,
textarea {
    width: 100%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box;
}

input:disabled,
textarea:disabled {
    background-color: #f5f7fa;
    cursor: not-allowed;
    opacity: 0.7;
}

@media print {

    body,
    html {
        margin: 0;
        padding: 0;
    }

    .header-actions {
        display: none;
    }

    .leave-adjustment-form {
        margin: 0;
        padding: 0;
        page-break-inside: avoid;
    }

    table {
        page-break-inside: avoid;
        border-collapse: collapse;
        box-shadow: none;
    }

    table th,
    table td {
        border: 1px solid #000;
    }

    input,
    textarea {
        border: none !important;
        background-color: transparent !important;
        text-align: center;
        resize: none;
    }

    .instructions {
        page-break-before: avoid;
    }

    .form-info {
        display: flex;
        justify-content: space-between;
        color: #767676 !important;
    }
}
</style>